package com.lyf.auth.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Component;

@Component
public class JwtUtil {
   public static void main(String[] args) throws Exception {
      JwtUtil util = new JwtUtil();
      String ab = util.createJWT("jwt", "{id:100,name:xiaohong}", 60000L);
      System.out.println(ab);
      String jwt = "eyJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiJEU1NGQVdEV0FEQVMuLi4iLCJzdWIiOiJ7aWQ6MTAwLG5hbWU6eGlhb2hvbmd9IiwidXNlcl9uYW1lIjoiYWRtaW4iLCJuaWNrX25hbWUiOiJEQVNEQTEyMSIsImV4cCI6MTUxNzgzNTEwOSwiaWF0IjoxNTE3ODM1MDQ5LCJqdGkiOiJqd3QifQ.G_ovXAVTlB4WcyD693VxRRjOxa4W5Z-fklOp_iHj3Fg";
      Claims c = util.parseJWT(jwt);
      System.out.println(c.getId());
      System.out.println(c.getIssuedAt());
      System.out.println(c.getSubject());
      System.out.println(c.getIssuer());
      System.out.println((String)c.get("uid", String.class));
   }

   public SecretKey generalKey() {
      String stringKey = "7786df7fc3a34e26a61c034d5ec8245d";
      byte[] encodedKey = "[B@63893cf9".getBytes();
      System.out.println(encodedKey);
      System.out.println(Base64.encodeBase64URLSafeString(encodedKey));
      SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "RSA");
      return key;
   }

   public String createJWT(String id, String subject, long ttlMillis) throws Exception {
      SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.RS256;
      long nowMillis = System.currentTimeMillis();
      Date now = new Date(nowMillis);
      Map<String, Object> claims = new HashMap();
      claims.put("uid", "DSSFAWDWADAS...");
      claims.put("user_name", "admin");
      claims.put("nick_name", "DASDA121");
      SecretKey key = this.generalKey();
      JwtBuilder builder = Jwts.builder().setClaims(claims).setId(id).setIssuedAt(now).signWith(signatureAlgorithm, key);
      if (ttlMillis >= 0L) {
         long expMillis = nowMillis + ttlMillis;
         Date exp = new Date(expMillis);
         builder.setExpiration(exp);
      }

      String token = builder.compact();
      System.out.println(token);
      return token;
   }

   public Claims parseJWT(String jwt) throws Exception {
      SecretKey key = this.generalKey();
      Claims claims = (Claims)Jwts.parser().setSigningKey(key).parseClaimsJws(jwt).getBody();
      return claims;
   }
}
